package com.example.a2209_shop.detail

import android.R.attr.thumb
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.util.Log
import android.view.ViewGroup.LayoutParams
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.a2209_shop.R
import com.example.a2209_shop.adapter.MyFragAdapter
import com.example.a2209_shop.database.DataBaseUtils
import com.example.a2209_shop.databinding.ActivityDetailBinding
import com.example.a2209_shop.fg.CommentFragment
import com.example.a2209_shop.fg.RecommendFragment
import com.example.base.entity.DetailEntity
import com.example.base.mvvm.BaseActivity
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMWeb


@Route(path = "/app/DetailActivity")
class DetailActivity :BaseActivity<ActivityDetailBinding,DetailViewModel>(){
    @Autowired
    @JvmField
    var goodsId = 0

    var imgpath = ""
    lateinit var goodsInfo:DetailEntity

    var flag = false//是否收藏过的标志  默认未收藏过

    val fragmentList = mutableListOf<Fragment>()//显示viewpager中的fragment
    val titles = mutableListOf<String>()//显示tab上的文字
    lateinit var myFragAdapter: MyFragAdapter
    override fun initData() {
        viewModel.detailSuccess.observe(this){
            if(it.code==200){
                binding.detail = it.data
                imgpath = it.data.goods_default_icon
                goodsInfo = it.data
                //先查询当前商品是否是收藏状态
                val detail = DataBaseUtils.getDb().getGoodsDao().selectStatus(goodsId)
                if(detail!=null){
                    binding.star.setImageResource(R.drawable.baseline_star_24)
                    flag = true//当前是收藏状态
                }else{
                    //保存观看过的记录
                    goodsInfo.type = 1
                    DataBaseUtils.getDb().getGoodsDao().insertGoods(goodsInfo)
                    flag = false//当前是未收藏状态
                }
            }else{
                ToastUtils.showLong("加载失败：${it.message}")
            }
        }
        viewModel.addSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                //添加动画
                val imageView = ImageView(this)
                val params = LayoutParams(200,200)
                imageView.layoutParams = params
                Glide.with(this).load(imgpath).into(imageView)
                binding.llDetail.addView(imageView)
                //获取屏幕宽度
                val width = windowManager.defaultDisplay.width.toFloat()
                val heigh = windowManager.defaultDisplay.height.toFloat()

                val translationX = ObjectAnimator.ofFloat(imageView,"translationX",0f,width)
                val translationY = ObjectAnimator.ofFloat(imageView,"translationY",0f,heigh)

                val rotation = ObjectAnimator.ofFloat(imageView,"rotation",0f,360f)

                val animatorSet = AnimatorSet()
                animatorSet.duration = 2000
                animatorSet.play(translationX).with(translationY).with(rotation)

                animatorSet.addListener(object :Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {
                    }

                    override fun onAnimationEnd(animation: Animator) {
                        binding.llDetail.removeView(imageView)
                    }

                    override fun onAnimationCancel(animation: Animator) {
                    }

                    override fun onAnimationRepeat(animation: Animator) {
                    }
                })

                animatorSet.start()
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)
        viewModel.detail(goodsId)
        //返回按钮
        binding.back.setOnClickListener {
            finish()
        }
        //加入购物车按钮
        binding.addCar.setOnClickListener {
            Log.i("Tag", "initView: $goodsId ")
            viewModel.addCar(1,goodsId)
        }


        binding.star.setOnClickListener {
            if(flag){//当前状态为收藏过的  点击时执行的是取消收藏的状态
                goodsInfo.type = 1
                DataBaseUtils.getDb().getGoodsDao().update(goodsInfo)
                flag = false
                binding.star.setImageResource(R.drawable.baseline_star_border_24)
            }else{
                goodsInfo.type = 2
                DataBaseUtils.getDb().getGoodsDao().update(goodsInfo)
                flag = true
                binding.star.setImageResource(R.drawable.baseline_star_24)
            }
        }

        binding.goodsCode.setOnClickListener {
            val barcodeEncoder = BarcodeEncoder()
            //BarcodeFormat.QR_CODE  二维码   BarcodeFormat.CODE_128  条形码
            val bitmap = barcodeEncoder.encodeBitmap(goodsInfo.goods_code,BarcodeFormat.CODE_128,400,200)
            binding.ivCode.setImageBitmap(bitmap)
        }

        binding.share.setOnClickListener {
            val web: UMWeb = UMWeb(goodsInfo.goods_default_icon)
            ShareAction(this)
                .withMedia(web)
                .setDisplayList(SHARE_MEDIA.QQ)
                .setCallback(object :UMShareListener{
                    override fun onStart(p0: SHARE_MEDIA?) {
                    }

                    override fun onResult(p0: SHARE_MEDIA?) {
                    }

                    override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                        Log.d("sss", "onError: ${p1?.message}")
                    }

                    override fun onCancel(p0: SHARE_MEDIA?) {
                    }
                })
                .open()

        }

        //tab+Vp
        fragmentList.add(CommentFragment())
        fragmentList.add(RecommendFragment())
        titles.add("评论")
        titles.add("推荐")
        myFragAdapter = MyFragAdapter(this,fragmentList)
        binding.vp.adapter = myFragAdapter
        //联动
        TabLayoutMediator(binding.tl,binding.vp,object:TabLayoutMediator.TabConfigurationStrategy{
            override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
               tab.text = titles[position]
            }
        }).attach()


    }

    override fun getViewModel()  = DetailViewModel::class.java

    override fun getLayout() = R.layout.activity_detail

}